//
//  MineViewController.m
//  StockNet
//
//  Created by 小焘无量 on 2023/1/5.
//

#import "MineViewController.h"
#import "MineHeaderTableViewCell.h"

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIBarButtonItem *navRightItem;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation MineViewController

#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:NotifiName_LoginStateChange object:nil];
    
    [self UIConfig];
    
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    if ([YTClient shared].isLogin) {
        [self getUserInfo];
    }
}

-(void)dealloc {
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - view layout
- (void)UIConfig {
    
    self.navigationItem.rightBarButtonItem = [YTClient shared].isLogin ? self.navRightItem : nil;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 150;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView registerNib:[UINib nibWithNibName:MineHeaderTableViewCellID bundle:nil] forCellReuseIdentifier:MineHeaderTableViewCellID];
    //    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    //    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
}


#pragma mark - Event Response
//通知消息
-(void)notificationAction:(NSNotification *)info {
    if ([info.name isEqualToString:NotifiName_LoginStateChange]) {
        [self.tableView reloadData];
        self.navigationItem.rightBarButtonItem = [YTClient shared].isLogin ? self.navRightItem : nil;
    }
}

#pragma mark - Delegate,DataSource


#pragma mark  UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MineHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MineHeaderTableViewCellID forIndexPath:indexPath];
    cell.needUpdate = YES;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - Network

-(void)getUserInfo {
    
    WeakSelf;
    [[APIManager manager] Get:URL_GetUserInfo parameters:nil success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        if (NET_RESULT_CODE == 200) {
            YTUser *user = [YTClient shared].user;
            NSInteger memberLevel = [responseObject[@"data"][@"level"] integerValue];
            NSInteger memberExpires = [responseObject[@"data"][@"memberExpires"] integerValue];
            if (user.level != memberLevel) {
                user.level = memberLevel;
                user.member_expires = memberExpires;
                [[YTClient shared] updateUser:user];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotifiName_MemberStateChange object:nil
                ];
                [weakSelf.tableView reloadData];
            }
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
    }];
    
    
}

-(void)loginOutNetwork {
    
    WeakSelf;
    [MBProgressHUD showLoadingMessage:nil view:self.view];
    [[APIManager manager] Get:URL_LoutOut parameters:nil success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        if (NET_RESULT_CODE == 200) {
            [[YTClient shared] logout];
        } else {
            NET_SHOW_MSG;
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        NET_SHOW_ERROR;
    }];
}


#pragma mark - Method
-(void)loginOut {
    WeakSelf;
    [UIAlertController alertWithController:[NSObject getCurrentViewController] title:nil message:@"确定要退出登录吗？" actionTitles:@[@"取消", @"确定"] actionOne:nil actionTwo:^{
        [weakSelf loginOutNetwork];
    }];
}

#pragma mark - Set Get

#pragma mark - Lazy
-(UIBarButtonItem *)navRightItem {
    if (!_navRightItem) {
        UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,60,30)];
        [rightButton setTitleColor:kNavTitleColor forState:UIControlStateNormal];
        [rightButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [rightButton setTitle:@"退出" forState:UIControlStateNormal];
        [rightButton setImage:ImageWithName(@"icon_login_logout") forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(loginOut)forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
        _navRightItem = rightItem;
    }
    return _navRightItem;
}
@end
